%Converts Syms variables into sdpvar().
%
%This function looks for Syms variables in alfa string vector and replace
%them with sdpvar() variables.
%
%Prorotype: [alfa] = convertToSdp(alfa).
%
%Input:     alfa - is a equation string vector with Syms variable.
%
%Output:    alfa -same alfa's syntax but with sdpvar() variable istead of Syms.

%Claudio Fantacci & Alessandro Martini.

function [ alfa ] = convertToSdp( alfa )

sdpIndex = 1;

for i = 1:length(alfa)
    target = char(alfa(i));
    if alfa(i) ~= 0 && isempty(strfind(target,'+')) && isempty(strfind(char(alfa(i)),'-')) && isempty(strfind(char(alfa(i)),'*'))
        names{sdpIndex} = target;
        sdpalfa{sdpIndex} = sdpvar(1);
        sdpIndex = sdpIndex + 1;
    end
end

for i = 1:length(alfa)
    if ~isempty(strfind(char(alfa(i)),'+')) || ~isempty(strfind(char(alfa(i)),'-')) || ~isempty(strfind(char(alfa(i)),'*'))
        chr = strrep(char(alfa(i)),'+',' +');
        chr = strrep(chr,'-',' -');
        chr = strrep(chr,'*','* ');
        pieces = strsplit(' ',chr);
        for k=1:length(names)
            nameToCheck = names{k};
            found = false;
            index = 1;
            while ~found && index <= length(pieces)
                pieceToControl = char(pieces{index});
                if ~isempty(strfind(pieceToControl,nameToCheck))
                    pieces{index} = sdpalfa{k};
                    found = true;
                else
                    index = index + 1;
                end
            end
        end
        result = '';
        for k = 1:length(pieces)
            if isempty(strfind(class(pieces{k}),'sdpvar'))
                result = strcat(result,char(pieces{k}));
            else
                string = cell2str(names{k});
                result = strcat(result,string);
            end
        end
        command = strcat('sdpalfa{',num2str(i),'}=',result,';');
        eval(command);
    end
    
end

return;
